package com.example.elderlycare.controller;

import com.example.elderlycare.controller.entity.EquipmentRequestBody;
import com.example.elderlycare.dao.entity.Equipment;
import com.example.elderlycare.service.EquipService;
import com.example.elderlycare.service.entity.EquipListResponseBody;
import com.example.elderlycare.utils.Result;
import com.example.elderlycare.utils.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/equip")
public class EquipmentController {
    private final Logger logger = LoggerFactory.getLogger(EquipmentController.class);

    @Resource
    EquipService equipService;

    /**
     * queryEquipmentList 根据条件获取设备列表
     *
     * @param type     设备类型
     * @param username 用户名称
     * @param number   用户省份证号
     * @param issue    发放方式
     * @param status   设备状态
     * @param online   isonline
     * @param pageSize 页面大小
     * @param current  当前页面
     * @return List
     */
    @GetMapping
    public Result<EquipListResponseBody> queryEquipmentList(
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "number", required = false) String number,
            @RequestParam(value = "issue", required = false) String issue,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "online", required = false) String online,
            @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
            @RequestParam(defaultValue = "1", value = "current") int current
    ) {
        Map<String, Object> params = new HashMap<>();
        if (type != null) {
            params.put("type", type);
        }
        if (username != null) {
            params.put("username", "%" + username + "%");
        }
        if (number != null){
            params.put("number", number);
        }
        if (issue != null){
            params.put("issue", issue);
        }
        if (status != null){
            params.put("status", status);
        }
        if (online != null) {
            params.put("online", online);
        }
        params.put("limit", pageSize);
        params.put("offset", (current - 1) * pageSize);
        EquipListResponseBody responseBody = equipService.queryEquipService(params);
        return Result.success(responseBody);
    }

    /**
     * addEquip 增加设备信息
     *
     * @param req AddEquipmentRequestBody
     * @return null
     */
    @PostMapping
    public Result<?> addEquip(@Valid @RequestBody EquipmentRequestBody.AddEquipmentRequestBody req) {
        Equipment.EquipmentBuilder equipmentBuilder = Equipment.builder().
                code(req.getCode()).
                modelName(req.getModelName()).
                simCode(req.getSimCode()).
                issuedAt(req.getIssuedAt()).
                isOnline(req.getIsOnline()).
                supplierId(req.getSupplierId()).
                equipTypeId(req.getEquipTypeId()).
                employeeId(req.getEmployeeId()).
                issueMethodId(req.getIssueMethodId()).
                berthId(req.getBerthId()).
                equipmentStatusId(req.getEquipmentStatusId());
        boolean success = equipService.save(equipmentBuilder.build());
        if (success) {
            return Result.success(null);
        } else {
            logger.warn("add elder error");
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * updateEquip 修改设备信息
     *
     * @param req UpdateEquipmentRequestBody
     * @return null
     */
    @PutMapping
    public Result<?> updateEquip(@Valid @RequestBody EquipmentRequestBody.UpdateEquipmentRequestBody req) {
        Equipment.EquipmentBuilder equipmentBuilder = Equipment.builder().
                id(req.getId()).
                code(req.getCode()).
                modelName(req.getModelName()).
                simCode(req.getSimCode()).
                issuedAt(req.getIssuedAt()).
                isOnline(req.getIsOnline()).
                supplierId(req.getSupplierId()).
                equipTypeId(req.getEquipTypeId()).
                employeeId(req.getEmployeeId()).
                issueMethodId(req.getIssueMethodId()).
                berthId(req.getBerthId()).
                equipmentStatusId(req.getEquipmentStatusId());
        boolean success = equipService.updateById(equipmentBuilder.build());
        if (success) {
            return Result.success(null);
        } else {
            logger.warn("update elder error");
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * deleteElder 通过id删除设备
     *
     * @param id 需要删除的设备id
     * @return null
     */
    @DeleteMapping
    public Result<?> deleteElder(@RequestParam("id") @NotEmpty Integer id) {
        boolean success = equipService.removeById(id);
        if (success) {
            logger.info("delete equip successfully");
            return Result.success(null);
        } else {
            logger.warn("delete equip error");
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }


    /**
     * queryEquipmentList 根据条件获取设备列表
     *
     * @param ids      选择的id
     * @param type     设备类型
     * @param username 用户名称
     * @param number   用户省份证号
     * @param issue    发放方式
     * @param status   设备状态
     * @param online   isonline
     * @return List
     */
    @GetMapping("/export")
    public Result<?> exportEquipmentList(
            HttpServletResponse response,
            @RequestParam(value = "id", required = false) List<Integer> ids,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "number", required = false) String number,
            @RequestParam(value = "issue", required = false) String issue,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "online", required = false) String online
    ) {
        Map<String, Object> params = new HashMap<>();
        params.put("ids", ids);
        params.put("type", type);
        params.put("username", username != null ? "%" + username + "%" : null);
        params.put("number", number);
        params.put("issue", issue);
        params.put("status", status);
        params.put("online", online);
        try {
            equipService.exportEquipList(response, params);
            return Result.success(null);
        } catch (IOException e) {
            logger.warn("IOException ", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }
}
